package com.ming_za.odupdaterserver.spring_modify;

import com.ming_za.odupdaterserver.core.interceptor.AdminVerificationInterceptor;
import com.ming_za.odupdaterserver.core.interceptor.GlobalInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import java.util.Collections;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final AdminVerificationInterceptor adminVerificationInterceptor;
    private final GlobalInterceptor globalInterceptor;

    public WebConfig(AdminVerificationInterceptor adminVerificationInterceptor, GlobalInterceptor globalInterceptor) {
        this.adminVerificationInterceptor = adminVerificationInterceptor;
        this.globalInterceptor = globalInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(adminVerificationInterceptor)
                .addPathPatterns("/sev-v/**");
        registry.addInterceptor(globalInterceptor)
                .addPathPatterns("/**");
    }

    @Bean
    public SimpleUrlHandlerMapping faviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Integer.MIN_VALUE);
        mapping.setUrlMap(Collections.singletonMap("/favicon.ico", faviconRequestHandler()));
        return mapping;
    }

    @Bean
    public ResourceHttpRequestHandler faviconRequestHandler() {
        ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
        requestHandler.setLocations(Collections.singletonList(new ClassPathResource("/")));
        return requestHandler;
    }

    //同源策略
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**")
//                .allowedOriginPatterns("*")
//                .allowCredentials(true)
//                .maxAge(3600)
//                .allowedHeaders("*")
//                .allowedMethods("*");
//    }
}
